/*
 * @Author: 鱿鱼溪学院
 * @Date: 2025-04-05 22:22:21
 * @LastEditTime: 2025-04-20 19:15:48
 * @LastEditors: 鱿鱼溪学院
 * @Description: 在这个文件中统一进行路由的注册，
 * @FilePath: \yyx_ser_ts\app\router\decorator\controller.ts
 * Copyright 鱿鱼溪学院 by edu v1.0
 * 天道酬勤
 */
import 'reflect-metadata'
import router from '../routerInstance'

/**
 * 从类原型的方法上获取元数据
 * @param target 类的原型对象
 * @param key 类的方法名
 */
function getMetadataFromMethod(target: any, key: string) {
  const path = Reflect.getMetadata('path', target, key)
  const method = Reflect.getMetadata('method', target, key)
  const middlewares = Reflect.getMetadata('middlewares', target, key) || []
  return { path, method, middlewares }
}

/**
 * 注册路由规则
 * @param router 路由实例
 * @param root 根路径
 * @param path 方法对应的路径
 * @param method 路由方法
 * @param middlewares 中间件数组
 * @param handler 处理函数
 */
function registerRoute(
  router: any,
  root: string,
  path: string,
  method: string,
  middlewares: any[],
  handler: any
) {
  const fullPath = root === '/' ? path : `${root}${path}`
  router[method](fullPath, ...middlewares, handler)
}

export function controller(root: string) {
  return function (target: new (...args: any[]) => any) {
    const handlerKeys = Object.getOwnPropertyNames(target.prototype).filter(
      (key) => key !== 'constructor'
    )

    handlerKeys.forEach((key) => {
      const { path, method, middlewares } = getMetadataFromMethod(
        target.prototype,
        key
      )
      const handler = target.prototype[key]

      if (path && method) {
        registerRoute(router, root, path, method, middlewares, handler)
        console.log(
          `${method.toUpperCase()} ${root}${path}`,
          '注册路由规则成功'
        )
      }
    })
  }
}
